<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :need-return="false"
      :btn-list="fullInfo.btnList"
    >
      <template v-slot:full-button>
        <ScanInputBox
          :query="scanInfo.query"
          :api="scanInfo.api"
          style="margin-right: 10px"
          @callback="onCallBackScanData"
        />
      </template>
      <!-- 主表信息 -->
      <div id="table-list">
        <div class="model-panel">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="1">
              <template #title>
                <div class="model-panel-title">
                  <p>{{ $t('basic_information') }}</p>
                </div>
              </template>
              <div class="model-panel-body">
                <!-- form -->
                <page-form
                  class="paddingBox order-model-formBox flex_wrap_start_start"
                  v-model:ref-obj="formInfo.ref"
                  :disabled="formInfo.disabled"
                  :data="formInfo.data"
                  :field-list="formInfo.fieldList"
                  :rules="formInfo.rules"
                  :label-width="formInfo.labelWidth"
                  @handleEvent="handleFormEvent"
                >
                  <template v-slot:form-depotName>
                    <el-input
                      v-model="formInfo.data.depotName"
                      class="not-br not-mongolia"
                      type="input"
                      :disabled="true"
                      placeholder="请选择仓库"
                    >
                      <template #append>
                        <el-icon @click="openDepotWindow"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:form-receiveAddressValue>
                    <el-input
                      v-model="formInfo.data.receiveAddressValue"
                      class="not-mongolia"
                      type="input"
                      :disabled="true"
                      placeholder="请选择收货地址"
                    >
                      <template #append>
                        <el-icon @click="openReceiveAddressWindow"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:form-filePathList>
                    <upload-img
                      v-model:value="formInfo.data.filePathList"
                      multiple
                      :action="action"
                      :limit="10"
                      :title="`附件`"
                      :responseFn="handleResponse"
                    />
                  </template>
                </page-form>
              </div>
            </el-collapse-item>
          </el-collapse>
          <!-- 明细信息 -->
          <div id="table-box" class="model-panel">
            <div class="model-panel-title">
              <Tooltip :text="$t('detailInfo')"></Tooltip>
            </div>
            <div class="model-panel-body">
              <!-- 条件栏 -->
              <NewPageFilter :filter-btn="filterInfo.btnList">
                <template v-if="!receiveAll" v-slot:filter-addProduct>
                  <el-button @click="addProduct">添加产品</el-button>
                </template>
                <template v-if="!receiveAll" v-slot:filter-remove>
                  <el-button
                    :disabled="!tableInfo.selections.length"
                    @click="remove"
                  >
                    删除产品
                  </el-button>
                </template>
                <template v-if="receiveAll" v-slot:filter-fill>
                  <el-button type="primary" @click="changeNumberAll('receive')"
                    >一键处理</el-button
                  >
                  <el-button type="primary" @click="changeNumberAll('refuse')"
                    >全部拒收</el-button
                  >
                  <el-button
                    type="primary"
                    @click="changeNumberAll('notOneKey')"
                    >一键取消</el-button
                  >
                </template>
                <template v-slot:filter-fillTem>
                  <el-input-number
                    v-model="filterInfo.data.tem"
                    controls-position="right"
                    style="width: 100px"
                    placeholder="温度"
                    :step="1"
                    :min="-100"
                    :max="100"
                  />
                  <el-button @click="changeNumberTemHum('tem')"
                    >温度设置</el-button
                  >
                </template>
                <template v-slot:filter-fillHum>
                  <el-input-number
                    v-model="filterInfo.data.hum"
                    controls-position="right"
                    style="width: 100px"
                    :min="0"
                    :max="100"
                    placeholder="湿度"
                    :precision="0"
                    :step="1"
                  >
                    <template #append>.com</template>
                  </el-input-number>
                  <el-button @click="changeNumberTemHum('hum')"
                    >湿度设置</el-button
                  >
                </template>
                <!-- <template v-slot:filter-rejectionReason>
                  <el-input
                    v-model="filterInfo.data.rejectionReason"
                    style="width: 100px"
                  >
                  </el-input>
                  <el-button @click="changeRejectionReason('rejectionReason')"
                    >拒收原因设置</el-button
                  >
                </template> -->
                <template v-slot:filter-packageMark>
                  <el-select
                    v-model.lazy="filterInfo.data.packageMark"
                    style="width: 130px"
                    placeholder="选择包装标识"
                    clearable
                    @change="changeSelectAll($event, 'package_mark')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'package_mark'
                      ]"
                      :key="index"
                      class="option"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-identifyMark>
                  <el-select
                    v-model.lazy="filterInfo.data.identifyMark"
                    clearable
                    style="width: 130px"
                    placeholder="选择确定标识"
                    @change="changeSelectAll($event, 'identify_mark')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'identify_mark'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-certificateMark>
                  <el-select
                    v-model.lazy="filterInfo.data.certificateMark"
                    clearable
                    style="width: 130px"
                    placeholder="选择证书标识"
                    @change="changeSelectAll($event, 'certificate_mark')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'certificate_mark'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-appearanceQuality>
                  <el-select
                    v-model.lazy="filterInfo.data.appearanceQuality"
                    clearable
                    style="width: 130px"
                    placeholder="选择外观质量"
                    @change="changeSelectAll($event, 'appearance_quality')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'appearance_quality'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-invalidReason>
                  <el-select
                    v-model.lazy="filterInfo.data.invalidReason"
                    clearable
                    style="width: 130px"
                    placeholder="选择不合格原因"
                    @change="changeSelectAll($event, 'invalid_reason')"
                  >
                    <el-option
                      v-for="(item, index) in $store.state.permission.dict[
                        'invalid_reason'
                      ]"
                      :key="index"
                      :value="item.code"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
                <template v-slot:filter-receiptNumber>
                  <el-input
                    v-model="filterInfo.data.receiptNumber"
                    style="width: 100px"
                    placeholder="发票号"
                    :maxlength="50"
                  />
                  <el-button @click="batchHandle()">发票号设置</el-button>
                </template>
              </NewPageFilter>
              <div class="tips-desc">
                <ModelTips
                  :items="modelTipsInfo.items"
                  :title="modelTipsInfo.title"
                  :brackets="true"
                />
                <span>&emsp;</span>
                <ModelTips
                  :items="modelTipsInfo1.items"
                  :title="modelTipsInfo1.title"
                  :brackets="true"
                />
              </div>

              <!-- 表格 -->
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data.async="tableInfo.list"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :index-method="indexMethod"
                  :check-box="true"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <el-form-item class="margin-bottom">
                        <div
                          v-if="
                            scope.row.codeType === 1 || scope.row.codeType === 4
                          "
                          class="page-table-input-number-wrapper"
                        >
                          <div class="page-table-input-number-left">
                            <div class="page-table-input-number-item">
                              <el-form-item
                                :prop="`data.${scope.$index}.largeUnitQty`"
                                :rules="
                                  scope.$index >= 0
                                    ? [
                                        {
                                          validator: $validate.positiveAndZero,
                                          trigger: 'blur',
                                        },
                                      ]
                                    : []
                                "
                              >
                                <el-input-number
                                  v-model.lazy="scope.row.largeUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="
                                    scope.row.qtyOperateMode === 0 ||
                                    scope.row.qtyOperateMode === 2
                                      ? 0
                                      : systemConfig.qty_show_precision
                                  "
                                  :min="0"
                                  :max="largeMax(scope.row)"
                                  @change="
                                    changeLarge(
                                      $event,
                                      scope.row,
                                      `data.${scope.$index}.largeUnitQty`
                                    )
                                  "
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.unitName }}
                              </div>
                            </div>
                            <div
                              v-if="
                                scope.row.unitConvertCoefficient > 1 &&
                                scope.row.qtyOperateMode === 2
                              "
                              class="page-table-input-number-item"
                            >
                              <el-form-item>
                                <el-input-number
                                  v-model.lazy="scope.row.smallUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="0"
                                  :min="0"
                                  :max="smallMax(scope.row)"
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.calcUnitName }}
                              </div>
                            </div>
                          </div>
                          <div
                            v-if="scope.row.qtyOperateMode === 2"
                            class="page-table-input-number-right"
                          >
                            {{ $fn.qtyFormatter(scope.row.qty) }}
                          </div>
                        </div>
                        <template
                          v-else-if="
                            scope.row.codeType === 2 || scope.row.codeType === 3
                          "
                        >
                          <el-switch
                            v-model="scope.row.receiveFlag"
                            active-color="#13ce66"
                            active-text="收"
                            @change="changeQtySwitch($event, scope.row)"
                          >
                          </el-switch>
                          <span class="qty-show">{{
                            $fn.qtyFormatter(scope.row.qty)
                          }}</span>
                        </template>
                      </el-form-item>
                    </template>
                    <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                  </template>
                  <template v-slot:col-refuseQty="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <el-form-item class="margin-bottom">
                        <div
                          v-if="
                            scope.row.codeType === 1 || scope.row.codeType === 4
                          "
                          class="page-table-input-number-wrapper"
                        >
                          <div class="page-table-input-number-left">
                            <div class="page-table-input-number-item">
                              <el-form-item
                                :prop="`data.${scope.$index}.refuseLargeUnitQty`"
                                :rules="
                                  scope.$index >= 0
                                    ? [
                                        {
                                          validator: $validate.positiveAndZero,
                                          trigger: 'blur',
                                        },
                                      ]
                                    : []
                                "
                              >
                                <el-input-number
                                  v-model.lazy="scope.row.refuseLargeUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="
                                    scope.row.qtyOperateMode === 0 ||
                                    scope.row.qtyOperateMode === 2
                                      ? 0
                                      : systemConfig.qty_show_precision
                                  "
                                  :min="0"
                                  :max="refuseLargeMax(scope.row)"
                                  @change="
                                    refuseChangeLarge(
                                      $event,
                                      scope.row,
                                      `data.${scope.$index}.refuseLargeUnitQty`
                                    )
                                  "
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.unitName }}
                              </div>
                            </div>
                            <div
                              v-if="
                                scope.row.unitConvertCoefficient > 1 &&
                                scope.row.qtyOperateMode === 2
                              "
                              class="page-table-input-number-item"
                            >
                              <el-form-item>
                                <el-input-number
                                  v-model.lazy="scope.row.refuseSmallUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="0"
                                  :min="0"
                                  :max="refuseSmallMax(scope.row)"
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.calcUnitName }}
                              </div>
                            </div>
                          </div>
                          <div
                            v-if="scope.row.qtyOperateMode === 2"
                            class="page-table-input-number-right"
                          >
                            {{ $fn.qtyFormatter(scope.row.refuseQty) }}
                          </div>
                        </div>
                        <template
                          v-else-if="
                            scope.row.codeType === 2 || scope.row.codeType === 3
                          "
                        >
                          <el-switch
                            v-model="scope.row.refuseFlag"
                            active-color="#13ce66"
                            active-text="拒"
                            @change="changeRefuseSwitch($event, scope.row)"
                          >
                          </el-switch>
                          <span class="qty-show">{{
                            $fn.qtyFormatter(scope.row.refuseQty)
                          }}</span>
                        </template>
                      </el-form-item>
                    </template>
                    <span v-else>{{
                      $fn.qtyFormatter(scope.row.refuseQty)
                    }}</span>
                  </template>
                  <template v-slot:col-tem="scope">
                    <el-input-number
                      v-if="!tableInfo.isSysGroup"
                      v-model="scope.row.tem"
                      controls-position="right"
                      style="width: 100px"
                      :step="1"
                    />
                    <span v-else>{{ scope.row.tem || 0 }}</span>
                  </template>
                  <!-- @change="changeTemHum($event, scope.row, 'tem')" -->
                  <template v-slot:col-hum="scope">
                    <el-input-number
                      v-if="!tableInfo.isSysGroup"
                      v-model="scope.row.hum"
                      controls-position="right"
                      style="width: 100px"
                      :min="0"
                      :max="100"
                      :precision="0"
                      :step="1"
                    />
                    <span v-else>{{ scope.row.hum || 0 }}</span>
                  </template>
                  <!--@change="changeTemHum($event, scope.row, 'hum')"-->
                  <template v-slot:col-price="scope">
                    <el-form-item
                      v-if="
                        tableInfo.isSysGroup
                          ? tableInfo.groupList.includes('price')
                          : true
                      "
                      :prop="`data.${scope.$index}.price`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positiveMoneyZero,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        v-model="scope.row.price"
                        controls-position="right"
                        style="width: 100px"
                        :min="0"
                        :max="999999999999999"
                        :precision="systemConfig.price_precision"
                        :step="1"
                        @change="
                          changeMoney(
                            $event,
                            scope.row,
                            `data.${scope.$index}.price`
                          )
                        "
                      />
                    </el-form-item>
                    <span v-else>{{
                      $fn.TripartiteMethod(scope.row.price)
                    }}</span>
                    <p
                      style="color: red"
                      v-if="
                        scope.row.isLimitPrice == 1 &&
                        scope.row.price > scope.row.purchaseLimitPrice
                      "
                    >
                      超过产品限价:{{ scope.row.purchaseLimitPrice }}
                    </p>
                  </template>
                  <template v-slot:col-packageMarkValue="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <select
                        v-model.lazy="scope.row.packageMark"
                        class="select"
                      >
                        <option
                          v-for="(item, index) in $store.state.permission.dict[
                            'package_mark'
                          ]"
                          :key="index"
                          class="option"
                          :value="item.code"
                        >
                          {{ item.name }}
                        </option>
                      </select>
                    </template>
                    <span v-else>{{ scope.row.packageMarkValue }}</span>
                  </template>
                  <template v-slot:col-identifyMarkValue="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <select
                        v-model.lazy="scope.row.identifyMark"
                        class="select"
                      >
                        <option
                          v-for="(item, index) in $store.state.permission.dict[
                            'identify_mark'
                          ]"
                          :key="index"
                          :value="item.code"
                        >
                          {{ item.name }}
                        </option>
                      </select>
                    </template>
                    <span v-else>{{ scope.row.identifyMarkValue }}</span>
                  </template>
                  <template v-slot:col-certificateMarkValue="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <select
                        v-model.lazy="scope.row.certificateMark"
                        class="select"
                      >
                        <option
                          v-for="(item, index) in $store.state.permission.dict[
                            'certificate_mark'
                          ]"
                          :key="index"
                          :value="item.code"
                        >
                          {{ item.name }}
                        </option>
                      </select>
                    </template>
                    <span v-else>{{ scope.row.certificateMarkValue }}</span>
                  </template>
                  <template v-slot:col-appearanceQualityValue="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <select
                        v-model.lazy="scope.row.appearanceQuality"
                        class="select"
                      >
                        <option
                          v-for="(item, index) in $store.state.permission.dict[
                            'appearance_quality'
                          ]"
                          :key="index"
                          :value="item.code"
                        >
                          {{ item.name }}
                        </option>
                      </select>
                    </template>
                    <span v-else>{{ scope.row.appearanceQualityValue }}</span>
                  </template>
                  <template v-slot:col-invalidReasonValue="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <select
                        v-model.lazy="scope.row.invalidReason"
                        class="select"
                      >
                        <option
                          v-for="(item, index) in $store.state.permission.dict[
                            'invalid_reason'
                          ]"
                          :key="index"
                          :value="item.code"
                        >
                          {{ item.name }}
                        </option>
                      </select>
                    </template>
                    <span v-else>{{ scope.row.invalidReasonValue }}</span>
                  </template>
                  <template v-slot:col-receiptNumber="scope">
                    <el-input
                      v-if="
                        formInfo.data.isEstimationStockBusiness != 1 &&
                        formInfo.data.isConsignBusiness != 1 &&
                        formInfo.data.isWayBill != 1 &&
                        systemConfig.receipt_together_config != 1
                      "
                      v-model="scope.row.receiptNumber"
                      disabled
                      :maxlength="50"
                    ></el-input>
                    <span v-else>{{ scope.row.receiptNumber || '-' }}</span>
                  </template>
                  <template v-slot:col-receiptPrice="scope">
                    <el-form-item
                      v-if="
                        formInfo.data.isWayBill != 1 &&
                        systemConfig.receipt_together_config != 1
                      "
                      :prop="`data.${scope.$index}[receiptPrice]`"
                    >
                      <el-input-number
                        v-model="scope.row.receiptPrice"
                        controls-position="right"
                        style="minwidth: 100px; margintop: 18px"
                        :precision="systemConfig.price_precision"
                        :step="1"
                        :min="0"
                        :max="999999999999999"
                        disabled
                        @change="
                          changePrice(
                            $event,
                            `data.${scope.$index}.receiptPrice`
                          )
                        "
                      />
                    </el-form-item>
                    <span v-else>{{ scope.row.receiptPrice || '-' }}</span>
                  </template>
                  <template v-slot:col-receiptCalcQty="scope">
                    <el-form-item
                      v-if="
                        formInfo.data.isEstimationStockBusiness != 1 &&
                        formInfo.data.isConsignBusiness != 1 &&
                        formInfo.data.isWayBill != 1 &&
                        systemConfig.receipt_together_config != 1
                      "
                      :prop="`data.${scope.$index}.receiptCalcQty`"
                    >
                      <el-input-number
                        v-model.lazy="scope.row.receiptCalcQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        disabled
                        controls-position="right"
                        :precision="systemConfig.qty_show_precision"
                        :min="0"
                        :max="receiptLargeMax(scope.row)"
                      />
                    </el-form-item>
                    <span v-else>{{ scope.row.receiptCalcQty || '-' }}</span>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 仓库选择框 -->
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :query="selectDepotInfo.query"
      :check-box="false"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <!-- 选择收货地址 -->
    <select-receive-address
      v-if="selectReceiveAddressInfo.visible"
      v-model:show-dialog="selectReceiveAddressInfo.visible"
      :query="selectReceiveAddressInfo.query"
      :check-box="false"
      :highlight-row="true"
      @callback="selectReceiveAddressCallback"
    />
    <single-product
      v-if="singleProductInfo.visible"
      v-model:show-dialog="singleProductInfo.visible"
      :query="singleProductInfo.query"
      :left-query="singleProductInfo.leftQuery"
      :left-customize-user-v-o="singleProductInfo.leftCustomizeUserVO"
      :table-data="$fn.deepClone(tableInfo.data)"
      :info="singleProductInfo.info"
      :settings="singleProductInfo.settings"
      :order-id="orderId"
      :deliver-id="deliverId"
      :query-params="filterInfo.query.queryParams"
      :fill-data="filterInfo.data"
      :group-list="tableInfo.groupList"
      :scan-info-query="scanInfo.query"
      :select-obj="singleProductInfo.selectObj"
      :left-detail-ids="singleProductInfo.leftDetailIds"
      :is-sys-group="tableInfo.isSysGroup"
      :isEstimationStockBusiness="formInfo.data.isEstimationStockBusiness"
      @callback="singleProductBack"
    >
    </single-product>
    <SelectDepotStorage
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :query="productInfo.query.queryMap"
      :query-params="filterInfo.query.queryParams"
      :left-table-key="productInfo.leftTableKey"
      :right-table-key="productInfo.rightTableKey"
      :api="productInfo.api"
      :exclude-query-list="productInfo.excludeQueryList"
      :show-price="$permission('receiving:price')"
      @callback="selectProduct"
    />
  </div>
</template>

<script setup name="receivingModify">
const SelectDepotStorage = defineAsyncComponent(() => import('./selectProduct'))
const ScanInputBox = defineAsyncComponent(() => import('./ScanInputBox'))
const SingleProduct = defineAsyncComponent(() => import('./singleProduct'))
import {
  getReceivingsScans,
  createReceivingOrder,
  handAddReceivingsAndSubmit,
  updateReceivingOrder,
  getReceivingDetailByDeliver,
  getReceivingOrderById,
  batchValidateReceivingOrder,
  receivingDetailsCustomizeListAll,
  getReceivingIndividualByDeliver,
  validateReceivingOrderNums,
} from '@/api/stock'
import { getDepotsDefault } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
// eslint-disable-next-line no-unused-vars
import _ from 'lodash'
import axios from 'axios'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const loading = ref(false)
const scrollTop = ref(0)
const box = ref(undefined)

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  orderId: {
    type: [Number, String],
  },
  deliverId: {
    type: [Number, String],
  },
  receiveAll: {
    type: Boolean,
  },
  isEstimated: {
    type: Boolean,
    default: false,
  },
})
const activeNames = ref(['1'])
const modelTipsInfo = ref({
  title: '默认单价与默认供应商价格是否相同',
  items: [
    {
      label: '不同',
      style: { width: '10px', height: '10px', background: '#f7c1c1' },
    },
  ],
})
const modelTipsInfo1 = ref({
  title: '扫码选中',
  items: [
    {
      label: '是',
      style: { width: '10px', height: '10px', background: '#c3f1d6' },
    },
  ],
})

const oldDataIndex = ref(-1)
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref([])
const scanInfo = reactive({
  api: getReceivingsScans,
  query: {
    receiveId: '',
    deliverId: '',
    customizeDto: {
      customizeUserVO: {},
      queryMap: {
        isConsignBusiness: {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: '',
        },
      },
    },
  },
})
//full组件信息
const fullInfo = reactive({
  visible: false,
  btnList: [
    {
      label: '保存并提交',
      event: saveAndSubmit,
      show: !props.orderId && proxy.$permission('receiving:saveAndSubmit'),
      loading: false,
    },
    { label: '保存', event: save, show: true, loading: false },
    { label: '返回', event: returnBank, show: true },
  ],
})
const formInfo = reactive({
  ref: null,
  data: {
    conclusion: '合格',
  },
  fieldList: [
    {
      label: '发货单号',
      value: 'deliverOrderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '采购单号',
      value: 'purchOrderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'input',
      disabled: true,
    },
    { label: '仓库', value: 'depotName', type: 'slot' },
    { label: '部门', value: 'deptName', type: 'input', disabled: true },
    { label: '收货地址', value: 'receiveAddressValue', type: 'slot' },

    {
      label: '收货联系人',
      value: 'receivingContacts',
      type: 'input',
    },
    {
      label: '联系人电话',
      value: 'receivingPhone',
      type: 'input',
    },
    // {
    //   label: '发票单号',
    //   value: 'invoiceNumber',
    //   type: 'input',
    // },
    // {
    //   label: '货单号',
    //   value: 'waybillNumber',
    //   type: 'input',
    // },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '是否暂估入库',
      value: 'isEstimationStockBusiness',
      type: 'select-model',
      code: 'default_no_or_yes',
      disabled: props.orderId || props.isEstimated ? true : false,
      checkDefault: false,
      event: 'isEstimationStockBusiness',
      show:
        proxy.$store.state.permission.systemConfig
          .is_estimation_stock_business == 1,
    },

    {
      label: '采购部门',
      value: 'purchDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '验收结论',
      value: 'conclusion',
      type: 'textarea',
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '发票号汇总',
      value: 'receiptNumber',
      type: 'input',
      disabled: true,
      show: true,
    },
    {
      label: '发票总金额',
      value: 'receiptSumAmount',
      type: 'input',
      disabled: true,
      show: true,
    },
    {
      label: '配送方式',
      value: 'deliveryType',
      type: 'select-model',
      code: 'delivery_type',
      clearable: true,
      disabled: true,
    },
    {
      label: '配送人',
      value: 'deliveryUser',
      type: 'input',
      disabled: true,
    },
    {
      label: '配送人电话',
      value: 'deliveryPhone',
      type: 'input',
      disabled: true,
    },

    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    depotName: [{ required: true, message: '请选择仓库', target: 'change' }],
    deptName: [{ required: true, message: '请输入部门', target: 'blur' }],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
    receivingPhone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      receiveAll: props.receiveAll,
      deliverId: '',
      receiveId: '',
    },
  },
  btnList: [
    { label: '添加产品', type: 'slot', value: 'addProduct' },
    { label: '删除产品', type: 'slot', value: 'remove' },
    { label: '一键填充', type: 'slot', value: 'fill' },
    { label: '温度填充', type: 'slot', value: 'fillTem' },
    { label: '湿度填充', type: 'slot', value: 'fillHum' },
    // { label: '拒收原因', type: 'slot', value: 'rejectionReason' },
    { label: '包装标识', type: 'slot', value: 'packageMark' },
    { label: '确定标识', type: 'slot', value: 'identifyMark' },
    { label: '合格证', type: 'slot', value: 'certificateMark' },
    { label: '外观质量', type: 'slot', value: 'appearanceQuality' },
    { label: '不合格原因值', type: 'slot', value: 'invalidReason' },
    {
      type: 'slot',
      value: 'receiptNumber',
      label: '一键设置发票号',
    },
  ],
  data: {
    hum: 0,
    tem: 0,
    packageMark: '',
    identifyMark: '',
    certificateMark: '',
    appearanceQuality: '',
    invalidReason: '',
    receiptNumber: '',
  },
  confirmData: {
    hum: 0,
    tem: 0,
    packageMark: '',
    identifyMark: '',
    certificateMark: '',
    appearanceQuality: '',
    invalidReason: '',
    packageMarkValue: '',
    identifyMarkValue: '',
    certificateMarkValue: '',
    appearanceQualityValue: '',
    invalidReasonValue: '',
  },
  flagVO: {
    humFlag: false,
    temFlag: false,
    packageMarkFlag: false,
    identifyMarkFlag: false,
    certificateMarkFlag: false,
    appearanceQualityFlag: false,
    invalidReasonFlag: false,
  },
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  sysGroup: [],
  groupList: [],
  isSysGroup: false,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'refuseQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'deliverQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'pendReceiveQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  batchNumberRules: [
    { required: true, message: '请输入批号', target: 'blur' },
    { required: true, message: '请输入批号', target: 'change' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '140',
    btList: [
      {
        label: '选择个体',
        event: singleProductDetails,
        show: true,
        ifRender: ifRenderSingle,
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: remove,
        show: proxy.$permission('receiving:del'),
        ifRender: ifRenderRemove,
      },
    ],
  },
})
const selectDepotInfo = reactive({
  visible: false,
  query: {
    status: '1',
    sort: 'create_time desc',
    depotAuth: 'id',
    useTypeId: '1',
    isCargoSpaceManage: '',
  },
})
let productInfo = reactive({
  visible: false,
  api: undefined,
  leftTableKey:
    'stockReceivingOrderQueryProduct-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  rightTableKey:
    'stockReceivingOrderQueryProductRight-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
  },
  excludeQueryList: [],
})
const singleProductInfo = reactive({
  visible: false,
  query: {
    orderId: {
      queryType: 'EQUALS',
      value: null,
    },
    id: {
      queryType: 'IN',
      value: null,
    },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
  leftQuery: {
    orderId: {
      queryType: 'EQUALS',
      value: null,
    },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
  leftCustomizeUserVO: {},
  info: {},
  selectObj: {},
  index: '',
  leftDetailIds: '',
  customizeUserVO: {},
  settings: {
    hum: false,
    tem: false,
    packageMark: false,
    identifyMark: false,
    certificateMark: false,
    appearanceQuality: false,
    invalidReason: false,
    rejectionReason: '',
  },
})

const listPage = ref('')

const selectReceiveAddressInfo = reactive({
  visible: false,
  query: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      val.forEach((item, index) => {
        item.tableIndex = index + 1
      })
    }
  }
)

watch(
  () => tableInfo.list,
  (val) => {
    //发票号汇总
    let receiptNumberArr = []
    let receiptSumAmount = 0
    val.forEach((row) => {
      if (row.receiptNumber) {
        receiptNumberArr.push(row.receiptNumber)
      }
      if (receiptNumberArr.length) {
        receiptNumberArr = [...new Set(receiptNumberArr)]
      }

      row.receiptSumAmount = proxy.$fn.accMul(
        row.receiptPrice || 0,
        row.receiptCalcQty || 0
      )
      receiptSumAmount = proxy.$fn.accAdd(
        row.receiptSumAmount,
        receiptSumAmount
      )
    })
    formInfo.data['receiptNumber'] = String(receiptNumberArr)
    formInfo.data['receiptSumAmount'] = receiptSumAmount
    if (val.length && !tableInfo.isSysGroup) {
      val.forEach((row) => {
        let smallUnitQty = row.smallUnitQty || 0
        let refuseSmallUnitQty = row.refuseSmallUnitQty || 0
        let unitConvertCoefficient = row.unitConvertCoefficient || 1
        let largeUnitQty = row.largeUnitQty || 0
        let refuseLargeUnitQty = row.refuseLargeUnitQty || 0
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let refuseCalcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(refuseLargeUnitQty, unitConvertCoefficient),
          refuseSmallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        let refuseQty = proxy.$fn.accDiv(refuseCalcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row['refuseCalcQty'] = refuseCalcQty
        row['refuseQty'] = refuseQty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, row.price),
          unitConvertCoefficient
        )
      })
    }
  },
  {
    deep: true,
  }
)
watch(
  () => formInfo.data.isConsignBusiness,
  (val) => {
    if (val == 1) {
      tableInfo.fieldList.forEach((item) => {
        if (
          item.value === 'receiptNumber' ||
          item.value === 'receiptPrice' ||
          item.value === 'receiptCalcQty' ||
          item.value === 'receiptSumAmount'
        ) {
          item.hidden = true
        }
      })
      formInfo.fieldList.forEach((item) => {
        if (
          item.value === 'receiptNumber' ||
          item.value === 'receiptSumAmount'
        ) {
          item.show = false
        }
      })
    }
  }
)
watch(
  () => formInfo.data.isEstimationStockBusiness,
  (val) => {
    if (val == 1) {
      tableInfo.fieldList.forEach((item) => {
        if (
          item.value === 'receiptNumber' ||
          item.value === 'receiptPrice' ||
          item.value === 'receiptCalcQty' ||
          item.value === 'receiptSumAmount'
        ) {
          item.hidden = true
        }
      })
      formInfo.fieldList.forEach((item) => {
        if (
          item.value === 'receiptNumber' ||
          item.value === 'receiptSumAmount'
        ) {
          item.show = false
        }
      })
    } else {
      tableInfo.fieldList.forEach((item) => {
        if (
          item.value === 'receiptNumber' ||
          item.value === 'receiptPrice' ||
          item.value === 'receiptCalcQty' ||
          item.value === 'receiptSumAmount'
        ) {
          item.hidden = false
        }
      })
      formInfo.fieldList.forEach((item) => {
        if (
          item.value === 'receiptNumber' ||
          item.value === 'receiptSumAmount'
        ) {
          item.show = true
        }
      })
    }
  }
)
let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  refuseQty: {
    label: '拒收数',
    value: 'refuseQty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'slot',
    permission: !proxy.$permission('receiving:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('receiving:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('receiving:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  defaultPrice: {
    label: '默认价格',
    value: 'defaultPrice',
    type: 'column',
    permission: !proxy.$permission('receiving:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  tem: {
    label: '到货温度',
    value: 'tem',
    type: 'slot',
    hidden: true,
  },
  hum: {
    label: '到货湿度',
    type: 'slot',
    value: 'hum',
    hidden: true,
  },
  packageMarkValue: {
    label: '包装标识',
    value: 'packageMarkValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  identifyMarkValue: {
    label: '确定标识',
    value: 'identifyMarkValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  certificateMarkValue: {
    label: '合格证',
    value: 'certificateMarkValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  appearanceQualityValue: {
    label: '外观质量',
    value: 'appearanceQualityValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  invalidReasonValue: {
    label: '不合格原因值',
    value: 'invalidReasonValue',
    type: 'slot',
    show: false,
    hidden: true,
  },
  receiptNumber: {
    label: '开票号',
    value: 'receiptNumber',
    type: 'slot',
    show: false,
    hidden: true,
  },
  receiptCalcQty: {
    label: '开票数量',
    value: 'receiptCalcQty',
    type: 'slot',
    show: false,
    hidden: true,
  },
  receiptPrice: {
    label: '开票单价',
    value: 'receiptPrice',
    type: 'slot',
    permission: !proxy.$permission('receiving:price'),
    show: false,
    hidden: true,
  },
  receiptSumAmount: {
    label: '开票金额',
    value: 'receiptSumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('receiving:price'),
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
let collapseHeight = ref()
const theResizeObserver = ref()
watch(
  () => collapseHeight.value,
  (val) => {
    if (val >= 340 || val <= 52) {
      proxy.$store.dispatch('app/togglePageTable')
    }
  },
  {
    immediate: true,
    deep: true,
  }
)
getCustomize()
getLeftCustomize()
getSingleVo()
onMounted(() => {
  proxy.$nextTick(() => {
    box.value = document.getElementById('newFullScreenScroll')
    box.value &&
      box.value.addEventListener('scroll', throttle(handleScroll, 30))
    theResizeObserver.value = new ResizeObserver(handleResize)
    const theElement = document.getElementsByClassName('el-collapse')[0]
    theResizeObserver.value.observe(theElement)
  })
})
onBeforeUnmount(() => {
  box.value &&
    box.value.removeEventListener('scroll', throttle(handleScroll, 30))
  theResizeObserver.value.disconnect()
})
function handleResize(entries) {
  collapseHeight.value =
    document.getElementsByClassName('el-collapse')[0].offsetHeight
}
function handleScroll() {
  // 获取eagleMapContainer的真实高度
  const box = document.getElementById('newFullScreenScroll')
  const boxHeight = box.offsetHeight
  // 获取table_list的真实高度（浮动内容的真实高度）
  const tableHeight = document.getElementById('table-list').offsetHeight
  const tableDom = document.getElementById('table-box')
  // boxHeight和滑块浮动的高度相差小于50 && 不在加载中 && 不是最后一页
  if (
    tableHeight - (box.scrollTop + boxHeight) < 50 &&
    !loading.value &&
    listPage.value + 1 < tableInfo.data.length / 50
  ) {
    // 第一次触发时，记录滑块高度
    // data里scrollTop，listPage默认为0
    if (!scrollTop.value) {
      scrollTop.value = box.scrollTop
    }
    // 触发下拉加载更多
    queryMoreStat(true, tableHeight, boxHeight)
  } else if (box.scrollTop <= tableDom.offsetTop + 200 && !loading.value) {
    // 如果滑块上拉到顶部，则向上加载50条
    queryMoreStat(false, tableHeight, boxHeight)
  }
}
function queryMoreStat(type, tableHeight, boxHeight) {
  loading.value = true
  // 触底加载
  if (type) {
    listPage.value = listPage.value + 1
    const centerPage = listPage.value * 50
    const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
    const endPage = centerPage + 50
    const newList = tableInfo.data.slice(startPage, endPage)
    if (listPage.value > 0) {
      const box = document.getElementById('newFullScreenScroll')
      // 视图跳到触发的数据，补回50的高度差值
      box.scrollTop = scrollTop.value - 50
    }
    tableInfo.list = newList
  } else {
    // 置顶加载
    if (listPage.value > 0) {
      listPage.value = listPage.value - 1
      const centerPage = listPage.value * 50
      const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
      const endPage = centerPage + 50
      const newList = tableInfo.data.slice(startPage, endPage)
      if (listPage.value > 0) {
        const tableDom = document.getElementById('table-box')
        const box = document.getElementById('newFullScreenScroll')
        // box.scrollTop = tableHeight - scrollTop.value - boxHeight

        box.scrollTop = tableDom.offsetTop + 220
      }
      tableInfo.list = newList
    } else {
      tableInfo.list = tableInfo.data.slice(0, 50)
    }
  }
  proxy.$nextTick(() => {
    loading.value = false
  })
}
function batchHandle() {
  //批量设置发票号
  let receiptNumber = filterInfo.data.receiptNumber
  if (receiptNumber) {
    if (tableInfo.selections.length) {
      tableInfo.selections.forEach((row) => {
        if (
          formInfo.data.isEstimationStockBusiness != 1 &&
          formInfo.data.isConsignBusiness != 1 &&
          formInfo.data.isWayBill != 1 &&
          systemConfig.value.receipt_together_config != 1
        ) {
          row['receiptNumber'] = receiptNumber
        }
      })
    } else {
      proxy.$message({
        message: '请选择需批量调发票号的明细！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  }
}
function indexMethod(row) {
  // const centerPage = listPage.value * 50
  // const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
  // return startPage + index + 1;
  return row.tableIndex
}

function getSummaries({ columns, data }) {
  const sums = []
  const tableData = tableInfo.data
  const summaryFieldList = tableInfo.summaryFieldList
  if (summaryFieldList.length === 0) return sums
  columns.forEach((column, index) => {
    let arrIndex = -1
    if (typeof summaryFieldList[0] === 'string') {
      arrIndex = _.findIndex(summaryFieldList, column.property)
    } else if (typeof summaryFieldList[0] === 'object') {
      arrIndex = _.findIndex(summaryFieldList, function (o) {
        return o.value === column.property
      })
    }
    if (arrIndex !== -1) {
      const values = tableData.map((item) => Number(item[column.property]))
      let formatter = summaryFieldList[arrIndex].formatter || ''
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            if (formatter) {
              return proxy.$fn.accAdd(
                proxy.$fn.TripartiteReturnNumber(formatter(prev)),
                proxy.$fn.TripartiteReturnNumber(formatter(curr))
              )
            } else {
              return proxy.$fn.accAdd(prev, curr)
            }
          } else {
            return prev
          }
        }, 0)
        if (formatter) {
          sums[index] = formatter(sums[index])
        }
      } else {
        sums[index] = ''
      }
    }
  })
  // if (checkBox.value) {
  //   sums[1] = "合计";
  // } else {
  sums[0] = '合计'
  // }
  return sums
}

function debounce(fn, delay) {
  let timer = null
  return function () {
    if (timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn, delay)
  }
}
function throttle(fn, delay) {
  let timer = null,
    startTime = new Date()
  return function () {
    let curTime = new Date()
    let remaining = delay - (curTime - startTime)
    clearTimeout(timer)
    if (remaining <= 0) {
      startTime = new Date()
      fn.apply(proxy, arguments)
    } else {
      timer = setTimeout(fn, remaining)
    }
  }
}

function handleResponse(response, file) {
  return file
}
function handleFormEvent(str, val) {
  if (str === 'isEstimationStockBusiness') {
    if (tableInfo.data.length) {
      tableInfo.data.forEach((row) => {
        if (val === '1') {
          row.isEstimationStockBusiness = '1'
          row.isEstimationStockBusinessValue = '是'
        } else if (val === '0') {
          row.isEstimationStockBusiness = '0'
          row.isEstimationStockBusinessValue = '否'
        }
        if (row.details && row.details.length) {
          row.details.forEach((item) => {
            if (val === '1') {
              item.isEstimationStockBusiness = '1'
              item.isEstimationStockBusinessValue = '是'
            } else if (val === '0') {
              item.isEstimationStockBusiness = '0'
              item.isEstimationStockBusinessValue = '否'
            }
          })
        }
      })
    }
  }
}

function changeSelectAll(val, str) {
  if (!val) {
    return
  }
  let obj = {
    package_mark: 'packageMark',
    identify_mark: 'identifyMark',
    certificate_mark: 'certificateMark',
    appearance_quality: 'appearanceQuality',
    invalid_reason: 'invalidReason',
  }
  let option = proxy.$store.state.permission.dict[str]
  let optionItem = option.find((item) => item.code === val)
  singleProductInfo.settings[obj[str]] = true
  filterInfo.confirmData[obj[str]] = val
  filterInfo.confirmData[obj[str] + 'Value'] = optionItem.name
  filterInfo.flagVO[obj[str] + 'Flag'] = true
  tableInfo.data.forEach((row) => {
    row[obj[str] + 'Value'] = optionItem.name
    row[obj[str]] = val
    if (row.details && row.details.length) {
      row.details.forEach((item) => {
        item[obj[str] + 'Value'] = optionItem.name
        item[obj[str]] = val
      })
    }
  })
}
function changeMoney(val, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  if (!tableInfo.isSysGroup) {
    tableInfo.data.forEach((item) => {
      if (item.productId === row.productId) {
        item.price = val
      }
    })
  } else {
    row.changePrice = true
    if (row.details && row.details.length) {
      let sumAmount = 0
      row.details.forEach((item) => {
        item.price = val
        item.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(val, item.calcQty),
          item.unitConvertCoefficient
        )
        sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount)
      })
      row.sumAmount = sumAmount
    } else {
      row.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(val, row.calcQty),
        row.unitConvertCoefficient
      )
    }
  }
}
function changeNumberAll(type) {
  if (tableInfo.isSysGroup) {
    tableInfo.data.forEach((row) => {
      let refuseSmallUnitQty = 0
      let refuseLargeUnitQty = 0
      let sumAmount = 0
      let refuseCalcQty = 0
      let unitConvertCoefficient = row.unitConvertCoefficient || 1
      row.fill = type
      if (row.details && row.details.length) {
        row.details.forEach((item) => {
          if (type === 'receive') {
            if (item.codeType === 4 || item.codeType === 1) {
              let num = proxy.$fn.Subtr(
                item.pendReceiveCalcQty,
                item.refuseCalcQty
              )
              if (num > 0) {
                item.calcQty = num
                if (item.qtyOperateMode === 2) {
                  item.largeUnitQty = parseInt(
                    item.calcQty / unitConvertCoefficient
                  )
                  item.smallUnitQty = parseInt(
                    item.calcQty % unitConvertCoefficient
                  )
                } else {
                  item.largeUnitQty = item.calcQty
                  item.smallUnitQty = 0
                }
                item.qty = proxy.$fn.accDiv(
                  item.calcQty,
                  unitConvertCoefficient
                )
                item.sumAmount = proxy.$fn.accDiv(
                  proxy.$fn.accMul(item.calcQty, item.price),
                  unitConvertCoefficient
                )
              }
              refuseLargeUnitQty = item.refuseLargeUnitQty
              refuseSmallUnitQty = item.refuseSmallUnitQty
              refuseCalcQty = item.refuseCalcQty
            } else if (item.codeType === 2 || item.codeType === 3) {
              if (item.qty === 0 && item.refuseQty === 0) {
                if (item.qtyOperateMode === 2) {
                  let largeUnitQty = parseInt(
                    item.pendReceiveCalcQty / unitConvertCoefficient
                  )
                  let smallUnitQty = parseInt(
                    item.pendReceiveCalcQty % unitConvertCoefficient
                  )
                  if (item.receiveFlag) {
                    item.largeUnitQty = largeUnitQty
                    item.smallUnitQty = smallUnitQty
                    item.qty = item.pendReceiveQty
                    item.calcQty = item.pendReceiveCalcQty
                    item.sumAmount = proxy.$fn.accDiv(
                      proxy.$fn.accMul(item.calcQty, item.price),
                      unitConvertCoefficient
                    )
                  } else {
                    item.refuseLargeUnitQty = largeUnitQty
                    item.refuseSmallUnitQty = smallUnitQty
                    item.refuseCalcQty = item.pendReceiveCalcQty
                    item.refuseQty = item.pendReceiveQty
                  }
                } else {
                  if (item.receiveFlag) {
                    item.largeUnitQty = item.pendReceiveQty
                    item.smallUnitQty = 0
                    item.qty = item.pendReceiveQty
                    item.calcQty = item.pendReceiveCalcQty
                    item.sumAmount = proxy.$fn.accDiv(
                      proxy.$fn.accMul(item.calcQty, item.price),
                      unitConvertCoefficient
                    )
                  } else {
                    item.refuseLargeUnitQty = item.pendReceiveQty
                    item.refuseSmallUnitQty = 0
                    item.refuseCalcQty = item.pendReceiveCalcQty
                    item.refuseQty = item.pendReceiveQty
                  }
                }
              }
              refuseSmallUnitQty = proxy.$fn.accAdd(
                item.refuseSmallUnitQty || 0,
                refuseSmallUnitQty
              )
              refuseLargeUnitQty = proxy.$fn.accAdd(
                item.refuseLargeUnitQty || 0,
                refuseLargeUnitQty
              )
              refuseCalcQty = proxy.$fn.accAdd(
                item.refuseCalcQty || 0,
                refuseCalcQty
              )
            }
          } else if (type === 'refuse') {
            item.refreshCalcQty = item.pendReceiveCalcQty
            item.refuseLargeUnitQty = parseInt(
              item.refuseCalcQty / unitConvertCoefficient
            )
            item.refuseSmallUnitQty = parseInt(
              item.refuseCalcQty % unitConvertCoefficient
            )
            item.refuseQty = proxy.$fn.accDiv(
              item.refuseCalcQty,
              unitConvertCoefficient
            )
            if (item.codeType === 2 || item.codeType === 3) {
              item.receiveFlag = false
            }
            item.calcQty = 0
            item.qty = 0
            item.largeUnitQty = 0
            item.smallUnitQty = 0
            item.sumAmount = 0
          }
        })
        if (type === 'receive') {
          row.calcQty = proxy.$fn.Subtr(
            row.pendReceiveCalcQty,
            refuseCalcQty || 0
          )
          if (row.qtyOperateMode === 2) {
            row.largeUnitQty = parseInt(row.calcQty / unitConvertCoefficient)
            row.smallUnitQty = parseInt(row.calcQty % unitConvertCoefficient)
          } else {
            row.largeUnitQty = row.calcQty
            row.smallUnitQty = 0
          }
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(row.calcQty || 0, row.price || 0),
            unitConvertCoefficient
          )
          row.qty = proxy.$fn.accDiv(row.calcQty, unitConvertCoefficient)
          row.refuseLargeUnitQty = refuseLargeUnitQty
          row.refuseSmallUnitQty = refuseSmallUnitQty
          row.refuseCalcQty = refuseCalcQty
          row.refuseQty = proxy.$fn.accDiv(
            refuseCalcQty,
            unitConvertCoefficient
          )
        } else if (type === 'refuse') {
          row.refuseCalcQty = row.pendReceiveCalcQty

          if (row.qtyOperateMode === 2) {
            row.refuseLargeUnitQty = parseInt(
              row.refuseCalcQty / unitConvertCoefficient
            )
            row.refuseSmallUnitQty = parseInt(
              row.refuseCalcQty % unitConvertCoefficient
            )
          } else {
            row.refuseLargeUnitQty = row.refuseCalcQty
            row.refuseSmallUnitQty = 0
          }
          row.sumAmount = 0
          row.refuseQty = proxy.$fn.accDiv(
            row.refuseCalcQty,
            unitConvertCoefficient
          )
          row.largeUnitQty = 0
          row.smallUnitQty = 0
          row.calcQty = 0
          row.qty = 0
        } else if (type === 'notOneKey') {
          row.largeUnitQty = 0
          row.smallUnitQty = 0
          row.refuseLargeUnitQty = 0
          row.refuseSmallUnitQty = 0
          row.qty = 0
          row.calcQty = 0
          row.refuseCalcQty = 0
          row.refuseQty = 0
          row.sumAmount = 0
          row.details = []
          row.groupConcatIds = ''
        }
      } else {
        if (type === 'receive') {
          row.calcQty = proxy.$fn.Subtr(
            row.pendReceiveCalcQty,
            row.refuseCalcQty
          )
          row.qty = proxy.$fn.accDiv(row.calcQty, unitConvertCoefficient)
          if (row.qtyOperateMode === 2) {
            row.largeUnitQty = parseInt(row.calcQty / unitConvertCoefficient)
            row.smallUnitQty = parseInt(row.calcQty % unitConvertCoefficient)
          } else {
            row.largeUnitQty = row.pendReceiveCalcQty
            row.smallUnitQty = 0
          }
          row.sumAmount = proxy.$fn.accAdd(
            sumAmount,
            proxy.$fn.accDiv(
              proxy.$fn.accMul(row.calcQty, row.price || 0),
              unitConvertCoefficient
            )
          )
        } else if (type === 'refuse') {
          row.refuseCalcQty = row.pendReceiveCalcQty
          row.refuseQty = proxy.$fn.accDiv(
            row.refuseCalcQty,
            unitConvertCoefficient
          )
          if (row.qtyOperateMode === 2) {
            row.refuseLargeUnitQty = parseInt(
              row.refuseCalcQty / unitConvertCoefficient
            )
            row.refuseSmallUnitQty = parseInt(
              row.refuseCalcQty % unitConvertCoefficient
            )
          } else {
            row.refuseLargeUnitQty = row.pendReceiveCalcQty
            row.refuseSmallUnitQty = 0
          }
          row.sumAmount = 0
          row.largeUnitQty = 0
          row.smallUnitQty = 0
          row.calcQty = 0
          row.qty = 0
        } else if (type === 'notOneKey') {
          row.largeUnitQty = 0
          row.smallUnitQty = 0
          row.refuseLargeUnitQty = 0
          row.qty = 0
          row.refuseSmallUnitQty = 0
          row.calcQty = 0
          row.refuseCalcQty = 0
          row.refuseQty = 0
          row.sumAmount = 0
          row.groupConcatIds = ''
        }
      }
    })
  } else {
    tableInfo.data.forEach((item) => {
      let unitConvertCoefficient = item.unitConvertCoefficient || 1
      if (type === 'receive') {
        if (item.codeType === 4 || item.codeType === 1) {
          item.calcQty = proxy.$fn.Subtr(
            item.pendReceiveCalcQty,
            item.refuseCalcQty
          )
          if (item.calcQty > 0) {
            if (item.qtyOperateMode === 2) {
              item.largeUnitQty = parseInt(
                item.calcQty / unitConvertCoefficient
              )
              item.smallUnitQty = parseInt(
                item.calcQty % unitConvertCoefficient
              )
            } else {
              item.largeUnitQty = item.calcQty
              item.smallUnitQty = 0
            }
            item.qty = proxy.$fn.accDiv(item.calcQty, unitConvertCoefficient)
            item.sumAmount = proxy.$fn.accDiv(
              proxy.$fn.accMul(item.calcQty, item.price),
              unitConvertCoefficient
            )
          }
        } else if (item.codeType === 2 || item.codeType === 3) {
          if (item.qty === 0 && item.refuseQty === 0) {
            item.receiveFlag = true
            if (item.qtyOperateMode === 2) {
              item.largeUnitQty = parseInt(
                item.pendReceiveCalcQty / unitConvertCoefficient
              )
              item.smallUnitQty = parseInt(
                item.pendReceiveCalcQty % unitConvertCoefficient
              )
            } else {
              item.largeUnitQty = item.pendReceiveQty
              item.smallUnitQty = 0
            }
            item.qty = item.pendReceiveQty
            item.calcQty = item.pendReceiveCalcQty
            item.sumAmount = proxy.$fn.accDiv(
              proxy.$fn.accMul(item.calcQty, item.price),
              unitConvertCoefficient
            )
          }
        }
      } else if (type === 'refuse') {
        row.refuseCalcQty = row.pendReceiveCalcQty
        row.refuseQty = proxy.$fn.accDiv(
          row.refuseCalcQty,
          unitConvertCoefficient
        )
        if (row.qtyOperateMode === 2) {
          row.refuseLargeUnitQty = parseInt(
            row.refuseCalcQty / unitConvertCoefficient
          )
          row.refuseSmallUnitQty = parseInt(
            row.refuseCalcQty % unitConvertCoefficient
          )
        } else {
          row.refuseLargeUnitQty = row.pendReceiveCalcQty
          row.refuseSmallUnitQty = 0
        }
        if (item.codeType === 2 || item.codeType === 3) {
          item.receiveFlag = false
        }
        row.sumAmount = 0
        row.largeUnitQty = 0
        row.smallUnitQty = 0
        row.calcQty = 0
        row.qty = 0
      } else if (type === 'notOneKey') {
        item.largeUnitQty = 0
        item.smallUnitQty = 0
        item.refuseLargeUnitQty = 0
        item.refuseSmallUnitQty = 0
        item.receiveFlag = false
        item.refuseFlag = false
        item.qty = 0
        item.calcQty = 0
        item.refuseQty = 0
        item.sumAmount = 0
      }
    })
  }
  console.log(tableInfo.data)
}
function changeNumberTemHum(str) {
  let data = filterInfo.data
  singleProductInfo.settings[str] = true
  filterInfo.flagVO[str + 'Flag'] = true
  filterInfo.confirmData[str] = data[str]
  tableInfo.data.forEach((row) => {
    if (row.details && row.details.length) {
      row.details.forEach((item) => {
        item[str] = data[str]
      })
    }
    row[str] = data[str]
  })
}
function changeRejectionReason(str) {
  let data = filterInfo.data
  singleProductInfo.settings[str] = true
  filterInfo.flagVO[str + 'Flag'] = true
  filterInfo.confirmData[str] = data[str]
  tableInfo.data.forEach((row) => {
    if (row.details && row.details.length) {
      row.details.forEach((item) => {
        item[str] = data[str]
      })
    }
    row[str] = data[str]
  })
}
function ifRenderSwitch() {
  return !tableInfo.isSysGroup
}
function ifRenderSingle() {
  return tableInfo.isSysGroup
}
function ifRenderRemove() {
  return !props.receiveAll
}
// 数量操作模式 qty_operate_mode：0整数模式，2自动算出小数，1手动输入小数
// 条码类型 code_type：1无码，2系统唯一码，3原厂码，4批次码
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.pendReceiveCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.pendReceiveCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function largeMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  if (row.qtyOperateMode === 2) {
    return parseInt(row.pendReceiveCalcQty / unitConvertCoefficient)
  } else {
    return row.pendReceiveQty
  }
}
function smallMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  let largeUnitQty = parseInt(row.pendReceiveCalcQty / unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.pendReceiveCalcQty % unitConvertCoefficient)
  } else {
    return unitConvertCoefficient - 1
  }
}
function refuseChangeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let refuseLargeUnitQty = parseInt(
    row.pendReceiveCalcQty / row.unitConvertCoefficient
  )

  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (refuseLargeUnitQty > 0 && e === refuseLargeUnitQty) {
      let refuseSmallUnitQty = parseInt(
        row.pendReceiveCalcQty % row.unitConvertCoefficient
      )
      if (row.refuseSmallUnitQty > refuseSmallUnitQty) {
        row.refuseSmallUnitQty = refuseSmallUnitQty
      }
    }
  }
}
function receiptLargeMax(row) {
  if (formInfo.data.isWayBill != 1) {
    return 99999999
  } else {
    return row.qty
  }
}
function refuseLargeMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  if (row.qtyOperateMode === 2) {
    return parseInt(row.pendReceiveCalcQty / unitConvertCoefficient)
  } else {
    return row.pendReceiveQty
  }
}
function refuseSmallMax(row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  let refuseLargeUnitQty = parseInt(
    row.pendReceiveCalcQty / unitConvertCoefficient
  )
  if (
    refuseLargeUnitQty === 0 ||
    row.refuseLargeUnitQty === refuseLargeUnitQty
  ) {
    return parseInt(row.pendReceiveCalcQty % unitConvertCoefficient)
  } else {
    return unitConvertCoefficient - 1
  }
}
function changeQtySwitch(e, row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  if (e) {
    if (unitConvertCoefficient == 1) {
      row.largeUnitQty = row.pendReceiveCalcQty / unitConvertCoefficient
    } else {
      row.largeUnitQty = parseInt(
        row.pendReceiveCalcQty / unitConvertCoefficient
      )
    }
    row.smallUnitQty = parseInt(row.pendReceiveCalcQty % unitConvertCoefficient)
    row.refuseLargeUnitQty = 0
    row.refuseSmallUnitQty = 0
    row['refuseFlag'] = false
  } else {
    row.largeUnitQty = 0
    row.smallUnitQty = 0
  }
}
function changeRefuseSwitch(e, row) {
  let unitConvertCoefficient = row.unitConvertCoefficient || 1
  if (e) {
    if (unitConvertCoefficient == 1) {
      row.refuseLargeUnitQty = row.pendReceiveCalcQty / unitConvertCoefficient
    } else {
      row.refuseLargeUnitQty = parseInt(
        row.pendReceiveCalcQty / unitConvertCoefficient
      )
    }
    row.refuseSmallUnitQty = parseInt(
      row.pendReceiveCalcQty % unitConvertCoefficient
    )
    row.largeUnitQty = 0
    row.smallUnitQty = 0
    row['receiveFlag'] = false
  } else {
    row.refuseLargeUnitQty = 0
    row.refuseSmallUnitQty = 0
  }
}
function onCallBackScanData(obj) {
  let { mergeDetail, detail } = obj
  let isSysGroup = tableInfo.isSysGroup
  let selectObj = singleProductInfo.selectObj
  let curIndex = 0
  if (!props.receiveAll) {
    mergeDetail.fill = 'notOneKey'
  }
  setChioceFalse()
  if (systemConfig.value.is_estimation_stock_business == 1) {
    if (formInfo.data.isEstimationStockBusiness == '1') {
      mergeDetail.isEstimationStockBusiness = '1'
      mergeDetail.isEstimationStockBusinessValue = '是'
      detail.isEstimationStockBusiness = '1'
      detail.isEstimationStockBusinessValue = '是'
    } else if (formInfo.data.isEstimationStockBusiness == '0') {
      mergeDetail.isEstimationStockBusiness = '0'
      mergeDetail.isEstimationStockBusinessValue = '否'
      detail.isEstimationStockBusiness = '0'
      detail.isEstimationStockBusinessValue = '否'
    }
  }
  mergeDetail = setAllChange(mergeDetail)
  detail = setAllChange(detail)
  if (isSysGroup) {
    let key = ''
    for (let item in selectObj) {
      key = key + mergeDetail[item] + '&'
    }
    mergeDetail.key = key
  } else {
    mergeDetail.key = generateProductKey(mergeDetail)
  }
  let item = tableInfo.data.filter((item) => item.key === mergeDetail.key)
  let itemIndex = tableInfo.data.findIndex(
    (item) => item.key === mergeDetail.key
  )
  if (item.length) {
    detail.price = item[0].price
    mergeDetail.price = item[0].price
  }
  if (isSysGroup) {
    if (item.length) {
      item[0].isChoice = true
      if (
        item[0].pendReceiveCalcQty <=
        proxy.$fn.accAdd(item[0].calcQty || 0, item[0].refuseCalcQty || 0)
      ) {
        proxy.$message({
          message: `当前产品已处理完`,
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        curIndex = itemIndex
        listPage.value = Math.floor(curIndex / 50)
        const centerPage = listPage.value * 50
        const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
        const endPage = centerPage + 50
        tableInfo.list = tableInfo.data.slice(startPage, endPage)
        oldDataIndex.value = curIndex
        return
      }
      if (item[0].details && item[0].details.length) {
        let index = item[0].details.findIndex((item) => {
          let rowKey = generateProductKey(item)
          return rowKey === generateProductKey(detail)
        })

        if (index !== -1) {
          let newItem = item[0].details[index]
          newItem.isChoice = true
          if (newItem.codeType === 4) {
            if (
              proxy.$fn.accAdd(newItem.calcQty, newItem.refuseCalcQty) >=
              newItem.pendReceiveCalcQty
            ) {
              proxy.$message({
                message: `当前产品已处理完`,
                type: 'warning',
                duration: 3500,
                showClose: true,
              })
            } else {
              let num = proxy.$fn.Subtr(
                newItem.pendReceiveCalcQty,
                proxy.$fn.accAdd(newItem.calcQty, newItem.refuseCalcQty)
              )
              let unitConvertCoefficient = newItem.unitConvertCoefficient || 1
              if (num >= unitConvertCoefficient) {
                newItem.calcQty = proxy.$fn.accAdd(
                  unitConvertCoefficient,
                  newItem.calcQty
                )
                if (newItem.qtyOperateMode === 2) {
                  newItem.largeUnitQty = parseInt(
                    newItem.calcQty / newItem.unitConvertCoefficient
                  )
                  newItem.smallUnitQty = parseInt(
                    newItem.calcQty % newItem.unitConvertCoefficient
                  )
                } else if (
                  newItem.qtyOperateMode === 0 ||
                  newItem.qtyOperateMode === 1
                ) {
                  newItem.largeUnitQty = newItem.calcQty
                  newItem.smallUnitQty = 0
                }
              } else {
                newItem.calcQty = proxy.$fn.accAdd(num, newItem.calcQty)
                if (newItem.qtyOperateMode === 2) {
                  newItem.largeUnitQty = parseInt(
                    newItem.calcQty / newItem.unitConvertCoefficient
                  )
                  newItem.smallUnitQty = parseInt(
                    newItem.calcQty % newItem.unitConvertCoefficient
                  )
                } else if (
                  newItem.qtyOperateMode === 0 ||
                  newItem.qtyOperateMode === 1
                ) {
                  newItem.largeUnitQty = newItem.calcQty
                  newItem.smallUnitQty = 0
                }
              }
              newItem.sumAmount = proxy.$fn.accDiv(
                proxy.$fn.accMul(newItem.calcQty, newItem.price),
                unitConvertCoefficient
              )
              item[0].details[index] = newItem
              item[0] = setMergeDetail(item[0])
              successInfo()
            }
          } else if (newItem.codeType === 2 || newItem.codeType === 3) {
            if (newItem.qty === 0 && newItem.refuseQty === 0) {
              if (newItem.qtyOperateMode === 2) {
                let largeUnitQty = parseInt(
                  newItem.pendReceiveCalcQty / newItem.unitConvertCoefficient
                )
                let smallUnitQty = parseInt(
                  newItem.pendReceiveCalcQty % newItem.unitConvertCoefficient
                )
                if (newItem.receiveFlag) {
                  newItem.largeUnitQty = largeUnitQty
                  newItem.smallUnitQty = smallUnitQty
                } else {
                  newItem.refuseLargeUnitQty = largeUnitQty
                  newItem.refuseSmallUnitQty = smallUnitQty
                }
              } else {
                if (newItem.receiveFlag) {
                  newItem.largeUnitQty = newItem.pendReceiveQty
                  newItem.smallUnitQty = 0
                } else {
                  newItem.refuseLargeUnitQty = newItem.pendReceiveQty
                  newItem.refuseSmallUnitQty = 0
                }
              }
              item[0] = setMergeDetail(item[0])
              successInfo()
            } else {
              proxy.$message({
                message: `当前产品已处理完`,
                type: 'warning',
                duration: 3500,
                showClose: true,
              })
            }
          }
        } else {
          detail.hum = item[0].hum
          detail.tem = item[0].tem
          detail.price = item[0].price
          item[0].details.unshift(detail)
          item[0] = setMergeDetail(item[0])
          successInfo()
        }
      } else {
        if (item[0].groupConcatIds) {
          getDetails(detail, item[0])
        } else {
          detail.hum = item[0].hum
          detail.tem = item[0].tem
          detail.price = item[0].price
          if (item[0].details && item[0].details.length) {
            item[0].details.unshift(detail)
          } else {
            item[0].details = [detail]
          }
          item[0] = setMergeDetail(item[0])
          successInfo()
        }
      }
      curIndex = itemIndex
      listPage.value = Math.floor(curIndex / 50)
      const centerPage = listPage.value * 50
      const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
      const endPage = centerPage + 50
      tableInfo.list = tableInfo.data.slice(startPage, endPage)
      oldDataIndex.value = curIndex
    } else {
      mergeDetail.details = [detail]
      tableInfo.data.unshift(setMergeDetail(mergeDetail))
      successInfo()
      tableInfo.list = tableInfo.data.slice(0, 50)
      oldDataIndex.value = 1
    }
  } else {
    if (item.length) {
      let newItem = item[0]
      newItem.isChoice = true
      if (newItem.codeType === 4) {
        if (
          proxy.$fn.accAdd(newItem.calcQty, newItem.refuseCalcQty) >=
          newItem.pendReceiveCalcQty
        ) {
          proxy.$message({
            message: `当前产品已处理完`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
        } else {
          let num = proxy.$fn.Subtr(
            newItem.pendReceiveCalcQty,
            proxy.$fn.accAdd(newItem.calcQty, newItem.refuseCalcQty)
          )
          let unitConvertCoefficient = newItem.unitConvertCoefficient || 1
          if (num >= unitConvertCoefficient) {
            newItem.calcQty = proxy.$fn.accAdd(
              unitConvertCoefficient,
              newItem.calcQty
            )
            if (newItem.qtyOperateMode === 2) {
              newItem.largeUnitQty = parseInt(
                newItem.calcQty / newItem.unitConvertCoefficient
              )
              newItem.smallUnitQty = parseInt(
                newItem.calcQty % newItem.unitConvertCoefficient
              )
            } else if (
              newItem.qtyOperateMode === 0 ||
              newItem.qtyOperateMode === 1
            ) {
              newItem.largeUnitQty = newItem.calcQty
              newItem.smallUnitQty = 0
            }
          } else {
            newItem.calcQty = proxy.$fn.accAdd(num, newItem.calcQty)
            if (newItem.qtyOperateMode === 2) {
              newItem.largeUnitQty = parseInt(
                newItem.calcQty / newItem.unitConvertCoefficient
              )
              newItem.smallUnitQty = parseInt(
                newItem.calcQty % newItem.unitConvertCoefficient
              )
            } else if (
              newItem.qtyOperateMode === 0 ||
              newItem.qtyOperateMode === 1
            ) {
              newItem.largeUnitQty = newItem.calcQty
              newItem.smallUnitQty = 0
            }
          }
          newItem.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(newItem.calcQty, newItem.price),
            unitConvertCoefficient
          )
          item[0] = newItem
          successInfo()
        }
      } else if (newItem.codeType === 2 || newItem.codeType === 3) {
        if (newItem.qty === 0 && newItem.refuseQty === 0) {
          item[0].calcQty = detail.calcQty
          item[0].largeUnitQty = detail.largeUnitQty
          item[0].smallUnitQty = detail.smallUnitQty
          item[0].receiveFlag = true
          successInfo()
        } else {
          proxy.$message({
            message: `当前产品已处理完`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
        }
      }
      curIndex = itemIndex
      listPage.value = Math.floor(curIndex / 50)
      const centerPage = listPage.value * 50
      const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
      const endPage = centerPage + 50
      tableInfo.list = tableInfo.data.slice(startPage, endPage)
      oldDataIndex.value = curIndex
    } else {
      mergeDetail.calcQty = detail.calcQty
      mergeDetail.largeUnitQty = detail.largeUnitQty
      mergeDetail.smallUnitQty = detail.smallUnitQty
      if (mergeDetail.codeType === 2 || mergeDetail.codeType === 3) {
        mergeDetail.receiveFlag = true
      }
      tableInfo.data.unshift(mergeDetail)
      tableInfo.list = tableInfo.data.slice(0, 50)
      oldDataIndex.value = 1
    }
  }
  proxy.$forceUpdate()
}
function getDetails(data, item = undefined) {
  let params = {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: item.groupConcatIds,
      },
    },
    queryParams: filterInfo.query.queryParams,
    customizeUserVO: singleProductInfo.customizeUserVO,
  }
  let api = undefined
  if (props.deliverId) {
    api = getReceivingIndividualByDeliver
    params.queryMap.orderId.value = props.deliverId
  } else if (props.orderId) {
    api = receivingDetailsCustomizeListAll
    params.queryMap.orderId.value = props.orderId
  }
  api(params).then((res) => {
    if (res && res.success) {
      let rowKey = generateProductKey(data)
      let itemIndex = res.data.findIndex((item) => {
        if (rowKey === generateProductKey(item)) {
          return item
        }
      })
      if (itemIndex !== -1) {
        res.data.forEach((row, index) => {
          if (index === itemIndex) {
            row.isChoice = true
            if (row.codeType === 4) {
              if (
                proxy.$fn.accAdd(row.calcQty, row.refuseCalcQty) >=
                row.pendReceiveCalcQty
              ) {
                proxy.$message({
                  message: `当前产品已处理完`,
                  type: 'warning',
                  duration: 3500,
                  showClose: true,
                })
              } else {
                let num = proxy.$fn.Subtr(
                  row.pendReceiveCalcQty,
                  proxy.$fn.accAdd(row.calcQty, row.refuseCalcQty)
                )
                let unitConvertCoefficient = row.unitConvertCoefficient || 1
                if (num >= 1) {
                  row.calcQty = proxy.$fn.accAdd(
                    unitConvertCoefficient,
                    row.calcQty
                  )
                  if (row.qtyOperateMode === 2) {
                    row.largeUnitQty = parseInt(
                      row.calcQty / row.unitConvertCoefficient
                    )
                    row.smallUnitQty = parseInt(
                      row.calcQty % row.unitConvertCoefficient
                    )
                  } else if (
                    row.qtyOperateMode === 0 ||
                    row.qtyOperateMode === 1
                  ) {
                    row.largeUnitQty = row.calcQty
                    row.smallUnitQty = 0
                  }
                } else {
                  row.calcQty = proxy.$fn.accAdd(num, row.calcQty)
                  if (row.qtyOperateMode === 2) {
                    row.largeUnitQty = parseInt(
                      row.calcQty / row.unitConvertCoefficient
                    )
                    row.smallUnitQty = parseInt(
                      row.calcQty % row.unitConvertCoefficient
                    )
                  } else if (
                    row.qtyOperateMode === 0 ||
                    row.qtyOperateMode === 1
                  ) {
                    row.largeUnitQty = row.calcQty
                    row.smallUnitQty = 0
                  }
                }
                successInfo()
              }
            } else if (row.codeType === 2 || row.codeType === 3) {
              if (row.qty === 0 && row.refuseQty === 0) {
                res.data[index] = data
                successInfo()
              } else {
                proxy.$message({
                  message: `当前产品已处理完`,
                  type: 'warning',
                  duration: 3500,
                  showClose: true,
                })
              }
            }
          }
          if (row.calcQty === 0 && row.refuseCalcQty === 0) {
            row.receiveFlag = true
          }
        })
      } else {
        res.data.unshift(data)
      }
      if (props.deliverId) {
        let arr = []
        res.data.forEach((el) => {
          if (data.deliverDetailId === el.deliverDetailId) {
            arr.push(el)
          }
        })
        item.details = arr
      } else if (props.orderId) {
        item.details = res.data
      }
      item = setMergeDetail(item)
      proxy.$forceUpdate()
    }
  })
}
function successInfo() {
  proxy.$message({
    message: `扫码成功`,
    type: 'success',
    duration: 3500,
    showClose: true,
  })
}
function setMergeDetail(data) {
  let largeUnitQty = 0
  let refuseLargeUnitQty = 0
  let smallUnitQty = 0
  let refuseSmallUnitQty = 0
  let sumAmount = 0
  let unitConvertCoefficient = data.unitConvertCoefficient || 1
  data.details.forEach((item) => {
    largeUnitQty = proxy.$fn.accAdd(largeUnitQty, item.largeUnitQty)
    smallUnitQty = proxy.$fn.accAdd(smallUnitQty, item.smallUnitQty)
    refuseLargeUnitQty = proxy.$fn.accAdd(
      refuseLargeUnitQty,
      item.refuseLargeUnitQty
    )
    refuseSmallUnitQty = proxy.$fn.accAdd(
      refuseSmallUnitQty,
      item.refuseSmallUnitQty
    )
    sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount)
  })
  let calcQty = proxy.$fn.accAdd(
    proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
    smallUnitQty
  )
  let refuseCalcQty = proxy.$fn.accAdd(
    proxy.$fn.accMul(refuseLargeUnitQty, unitConvertCoefficient),
    refuseSmallUnitQty
  )
  data.sumAmount = sumAmount
  data.calcQty = calcQty
  data.refuseCalcQty = refuseCalcQty
  data.qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
  data.refuseQty = proxy.$fn.accDiv(refuseCalcQty, unitConvertCoefficient)
  return data
}
function generateProductKey(item) {
  let key =
    item.productId +
    '&' +
    item.batchNumber +
    '&' +
    item.validityDate +
    '&' +
    item.productionDate +
    '&' +
    item.defaultPrice +
    '&' +
    item.qrCode +
    '&' +
    item.uniqueCode +
    '&' +
    item.factorySubCode +
    '&' +
    item.factoryMainCode
  return key
}
function openDepotWindow() {
  if (
    proxy.$store.state.permission.systemConfig.is_estimation_stock_business == 1
  ) {
    if (formInfo.data.isEstimationStockBusiness == 1) {
      selectDepotInfo.query.isCargoSpaceManage = 0
    } else {
      selectDepotInfo.query.isCargoSpaceManage = ''
    }
  }
  selectDepotInfo.visible = true
}
function addProduct() {
  let api = undefined
  api = getReceivingIndividualByDeliver
  if (props.deliverId) {
    productInfo.query.queryMap.orderId.value = props.deliverId
  } else if (props.orderId) {
    productInfo.query.queryMap.orderId.value = formInfo.data.deliverOrderId
  }
  productInfo.query.queryMap.isConsignBusiness.value =
    formInfo.data.isConsignBusiness
  let map = []
  if (tableInfo.data.length) {
    tableInfo.data.forEach((item) => {
      //将返回的数据变成Map形式
      let key = []
      tableInfo.sysGroup.forEach((row) => {
        let obj = {}
        obj.columnName = row.columnName
        obj.asTbName = row.asTbName
        obj.value = item[row.key]
        key.push(obj)
      })
      map.push(key)
    })
  }
  productInfo.excludeQueryList = map
  productInfo.api = api
  productInfo.visible = true
}
function setChioceFalse() {
  tableInfo.data.forEach((row) => {
    row.isChoice = false
    if (row.details && row.details.length) {
      row.details.forEach((item) => {
        item.isChoice = false
      })
    }
  })
}
function selectProduct(data) {
  let selectObj = singleProductInfo.selectObj
  data.forEach((row) => {
    if (tableInfo.isSysGroup) {
      let key = ''
      for (let item in selectObj) {
        key = key + row[item] + '&'
      }
      row.key = key
      row = setMergeDetail(row)
    } else {
      row.key = generateProductKey(row)
    }
    if (systemConfig.value.is_estimation_stock_business == 1) {
      if (formInfo.data.isEstimationStockBusiness == '1') {
        row.isEstimationStockBusiness = '1'
        row.isEstimationStockBusinessValue = '是'
      } else if (formInfo.data.isEstimationStockBusiness == '0') {
        row.isEstimationStockBusiness = '0'
        row.isEstimationStockBusinessValue = '否'
      }
    }

    if (row.details && row.details.length) {
      // eslint-disable-next-line no-unused-vars
      row.details.forEach((item) => {
        item = setAllChange(item)
        if (systemConfig.value.is_estimation_stock_business == 1) {
          if (formInfo.data.isEstimationStockBusiness == '1') {
            item.isEstimationStockBusiness = '1'
            item.isEstimationStockBusinessValue = '是'
          } else if (formInfo.data.isEstimationStockBusiness == '0') {
            item.isEstimationStockBusiness = '0'
            item.isEstimationStockBusinessValue = '否'
          }
        }
      })
    }
    row.fill = 'notOneKey'
    row = setAllChange(row)
  })
  setChioceFalse()
  tableInfo.data = data.concat(tableInfo.data)
  tableInfo.list = tableInfo.data.slice(0, 50)
}
function setAllChange(item) {
  //设置温湿度等变化
  let settings = singleProductInfo.settings
  let filterInfoData = filterInfo.confirmData
  if (settings.hum) {
    item.hum = filterInfoData.hum
  }
  if (settings.tem) {
    item.tem = filterInfoData.tem
  }
  if (settings.packageMark) {
    item.packageMark = filterInfoData.packageMark
    item.packageMarkValue = filterInfoData.packageMarkValue
  }
  if (settings.identifyMark) {
    item.identifyMark = filterInfoData.identifyMark
    item.identifyMarkValue = filterInfoData.identifyMarkValue
  }
  if (settings.certificateMark) {
    item.certificateMark = filterInfoData.certificateMark
    item.certificateMarkValue = filterInfoData.certificateMarkValue
  }
  if (settings.appearanceQuality) {
    item.appearanceQuality = filterInfoData.appearanceQuality
    item.appearanceQualityValue = filterInfoData.appearanceQualityValue
  }
  if (settings.invalidReason) {
    item.invalidReason = filterInfoData.invalidReason
    item.invalidReasonValue = filterInfoData.invalidReasonValue
  }
  return item
}
function selectDepotCallBack(row) {
  if (row && row.id) {
    formInfo.data.depotName = row.name
    formInfo.data.depotId = row.id
    formInfo.data.deptId = row.deptId
    formInfo.data.deptName = row.deptName
  } else {
    formInfo.data.depotName = ''
    formInfo.data.depotId = ''
    formInfo.data.deptId = ''
    formInfo.data.deptName = ''
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function remove(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.list = tableInfo.list.filter((row) => row !== selectRow)
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.list = tableInfo.list.filter(
          (row) => !tableInfo.selections.includes(row)
        )
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
  oldDataIndex.value = -1
}
function tableRowClassName({ row }) {
  if (
    proxy.$fn.accAdd(row.calcQty, row.refuseCalcQty) > row.pendReceiveCalcQty ||
    (proxy.$store.state.permission.systemConfig
      .receiving_verify_different_supplier_price == 1 &&
      row.price !== row.defaultSupplierPrice)
  ) {
    return 'warning-row'
  }
  if (row.isChoice) {
    return 'success-row'
  }
  return ''
}
function singleProductDetails(row, index) {
  singleProductInfo.info = proxy.$fn.deepClone(row)
  singleProductInfo.query.id.value = row.groupConcatIds
  singleProductInfo.leftDetailIds = row.leftDetailIds
  if (props.deliverId) {
    singleProductInfo.query.orderId.value = props.deliverId
    singleProductInfo.leftQuery.orderId.value = props.deliverId
  } else if (props.orderId) {
    singleProductInfo.query.orderId.value = props.orderId
  }
  singleProductInfo.query.isConsignBusiness.value =
    formInfo.data.isConsignBusiness
  singleProductInfo.leftQuery.isConsignBusiness.value =
    formInfo.data.isConsignBusiness
  for (let key in singleProductInfo.selectObj) {
    singleProductInfo.leftQuery[key] = {
      queryType: 'EQUALS',
      ignoreEmptyValue: false,
      value: key === 'price' ? row['defaultPrcie'] : row[key],
    }
  }
  singleProductInfo.index = index
  singleProductInfo.visible = true
}
function singleProductBack(data) {
  let index = singleProductInfo.index
  tableInfo.list[index] = data
  let tableIndex = tableInfo.data.findIndex((item) => item.key === data.key)
  tableInfo.data[tableIndex] = data
  if (data.changePrice) {
    let val = data.price
    tableInfo.list.forEach((row) => {
      if (row.productId === data.productId) {
        row.changePrice = true
        row.price = val
        if (row.details && row.details.length) {
          let sumAmount = 0
          row.details.forEach((item) => {
            item.price = val
            item.sumAmount = proxy.$fn.accDiv(
              proxy.$fn.accMul(val, item.calcQty),
              item.unitConvertCoefficient
            )
            sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount)
          })
          row.sumAmount = sumAmount
        } else {
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(val, row.calcQty),
            row.unitConvertCoefficient
          )
        }
      }
    })
    tableInfo.data.forEach((row) => {
      if (row.productId === data.productId) {
        row.changePrice = true
        row.price = val
        if (row.details && row.details.length) {
          let sumAmount = 0
          row.details.forEach((item) => {
            item.price = val
            item.sumAmount = proxy.$fn.accDiv(
              proxy.$fn.accMul(val, item.calcQty),
              item.unitConvertCoefficient
            )
            sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount)
          })
          row.sumAmount = sumAmount
        } else {
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(val, row.calcQty),
            row.unitConvertCoefficient
          )
        }
      }
    })
  }
}
function getDepotsDefaults() {
  let systemConfig = proxy.$store.state.permission.systemConfig
  if (systemConfig.default_receive_depot == 1) {
    //查询默认仓库
    getDepotsDefault().then((resp) => {
      if (resp && resp.success) {
        let data = resp.data
        if (data) {
          formInfo.data.depotName = data.name
          formInfo.data.depotId = data.id
          formInfo.data.deptName = data.deptName
          formInfo.data.deptId = data.deptId
        }
      }
    })
  } else if (systemConfig.default_receive_depot == 2) {
    let depotName = proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
      : ''
    formInfo.data.depotName = depotName
    formInfo.data.depotId = proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : ''
    let deptName = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : ''
    formInfo.data.deptName = deptName
    formInfo.data.deptId = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : ''
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let mergeDetails = proxy.$fn
      .deepClone(tableInfo.data)
      .filter((row) => row.qty > 0 || row.refuseQty > 0)
    if (!mergeDetails.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    let arr = mergeDetails.filter((item) => item.price == 0 || !item.price)
    if (arr.length) {
      proxy
        .$confirm(`存在价格为0的数据，是否继续保存?`, '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
        })
        .then(() => {
          realSave(mergeDetails, isSaveAndSubmit)
          return
        })
        .catch(() => {
          return
        })
    } else {
      realSave(mergeDetails, isSaveAndSubmit)
    }
  })
}
function realSave(mergeDetails, isSaveAndSubmit) {
  let receiptErr = []
  let qtyErr = []
  tableInfo.data.forEach((item) => {
    // 非货票同行  普通收货时    开票数量 以及开票号  要么一起填  要么 一起不填 不能只填一个   货票同行情况 不管
    if (
      !(item.receiptCalcQty && item.receiptNumber) &&
      (item.receiptCalcQty || item.receiptNumber) &&
      formInfo.data.isWayBill != 1
    ) {
      receiptErr.push(item.commonName)
    }
    if (
      formInfo.data.isWayBill != 1 &&
      systemConfig.value.receipt_together_config != 1 &&
      (item.receiptCalcQty || 0) > item.qty
    ) {
      qtyErr.push(item.commonName)
    }
  })
  if (receiptErr && receiptErr.length) {
    proxy.$message.warning(
      '请输入产品' + String(receiptErr) + '的开票数量、开票号'
    )
    return
  }
  if (qtyErr && qtyErr.length) {
    proxy.$message.warning(
      '产品' + String(qtyErr) + '的开票数量应该小于等于收货数量'
    )
    return
  }
  let commonName = mergeDetails
    .filter(
      (item) =>
        proxy.$fn.accAdd(item.calcQty, item.refuseCalcQty) >
        item.pendReceiveCalcQty
    )
    .map((item) => item.commonName)
  if (commonName.length) {
    proxy.$alert(
      `产品【${commonName}】的接收数与拒收数之和不能大于待收货数量`,
      '操作提示',
      {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
      }
    )
    return
  }
  mergeDetails.forEach((item) => {
    item.receiptQty = item.receiptCalcQty
  })
  if (
    proxy.$store.state.permission.systemConfig
      .receiving_verify_different_supplier_price == 1
  ) {
    let priceCheck = mergeDetails
      .filter((row) => row.defaultSupplierPrice !== row.price)
      .map((item) => item.commonName)
    if (priceCheck.length) {
      proxy
        .$confirm(`产品【${priceCheck}】存在价格差异，是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
        })
        .then(() => {
          sumbit(mergeDetails, isSaveAndSubmit)
          return
        })
        .catch(() => {
          return
        })
    } else {
      sumbit(mergeDetails, isSaveAndSubmit)
    }
  } else {
    sumbit(mergeDetails, isSaveAndSubmit)
  }
}
function sumbit(mergeDetails, isSaveAndSubmit) {
  formInfo.data.groupFlag = tableInfo.isSysGroup
  if (!tableInfo.isSysGroup) {
    mergeDetails = mergeDetails.map((item) => {
      if (!item.details) {
        let arr = []
        arr[0] = item
        item = {
          details: arr,
          ...item,
        }
        return item
      }
    })
  }
  mergeDetails.forEach((item) => {
    item.flagVO = filterInfo.flagVO
  })
  formInfo.data.mergeDetails = proxy.$fn.filterBlacklist(mergeDetails)
  batchValidateReceivingOrder(formInfo.data).then((resp) => {
    if (resp && resp.success) {
      let api = undefined
      if (props.orderId) {
        api = updateReceivingOrder
      } else if (props.deliverId) {
        formInfo.data.receiveAll = props.receiveAll
        api =
          isSaveAndSubmit === true
            ? handAddReceivingsAndSubmit
            : createReceivingOrder
      }
      validateReceivingOrderNums(formInfo.data).then((resp) => {
        if (resp.code === 200) {
          api(formInfo.data).then((resp) => {
            if (resp && resp.success) {
              showDialog.value = false
              emit('returnModify')
            }
          })
        }
      })
    }
  })
}
function returnBank() {
  showDialog.value = false
  emit('returnModify', 'back')
}
function getReceivingByDeliverId() {
  let query = proxy.$fn.deepClone(filterInfo.query)
  query.queryParams.pendReceiveGtZero = true
  getReceivingDetailByDeliver(query).then((res) => {
    if (res && res.success) {
      if (props.isEstimated) {
        res.data.isEstimationStockBusiness = 1
        res.data.isEstimationStockBusinessValue = '是'
      }
      let selectObj = singleProductInfo.selectObj
      if (res.data.mergeDetails && res.data.mergeDetails.length) {
        res.data.mergeDetails.forEach((row) => {
          if (tableInfo.isSysGroup) {
            let key = ''
            for (let item in selectObj) {
              key = key + row[item] + '&'
            }
            row.key = key
            row.fill = 'notOneKey'
          } else {
            row.key = generateProductKey(row)
          }
        })
        tableInfo.data = res.data.mergeDetails
        tableInfo.list = tableInfo.data.slice(0, 50)
      }
      formInfo.data = res.data
      formInfo.data.conclusion = res.data.conclusion || '合格'

      setBusinessDate()
      scanInfo.query.customizeDto.queryMap.isConsignBusiness.value =
        res.data.isConsignBusiness

      getDepotsDefaults()
    }
  })
}
function getMain() {
  getReceivingOrderById(props.orderId).then((res) => {
    if (res && res.success) {
      if (props.isEstimated) {
        res.data.isEstimationStockBusiness = 1
        res.data.isEstimationStockBusinessValue = '是'
      }
      scanInfo.query.deliverId = res.data.deliverOrderId
      scanInfo.query.receiveId = props.orderId
      scanInfo.query.customizeDto.queryMap.isConsignBusiness.value =
        res.data.isConsignBusiness
      singleProductInfo.leftQuery.orderId.value = res.data.deliverOrderId
      filterInfo.query.queryParams.deliverId = res.data.deliverOrderId
      filterInfo.query.queryParams.receiveId = props.orderId
      formInfo.data = res.data
      formInfo.data.conclusion = res.data.conclusion || '合格'
      setBusinessDate()
      if (res.data.isEstimationStockBusiness == 1) {
        selectDepotInfo.query.isCargoSpaceManage = 0
      } else {
        selectDepotInfo.query.isCargoSpaceManage = ''
      }
      getList()
    }
  })
}
function getList() {
  receivingDetailsCustomizeListAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      let selectObj = singleProductInfo.selectObj
      res.data.forEach((row) => {
        if (tableInfo.isSysGroup) {
          let key = ''
          for (let item in selectObj) {
            key = key + row[item] + '&'
          }
          row.key = key
          row.fill = 'notOneKey'
        } else {
          row.key = row.productId + '&'
        }
      })
      tableInfo.data = res.data
      tableInfo.list = tableInfo.data.slice(0, 50)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'stockReceivingOrderModify-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  }
  tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let obj = {}
      let arr = []
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true
          arr.push(key)
          obj[key] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            ignoreEmptyValue: false,
            value: null,
          }
        }
      }
      singleProductInfo.selectObj = obj
      tableInfo.groupList = arr
      filterInfo.query.customizeUserVO = data
      scanInfo.query.customizeDto.customizeUserVO = data
      if (props.deliverId) {
        filterInfo.query.queryMap.orderId.value = props.deliverId
        scanInfo.query.deliverId = props.deliverId
        filterInfo.query.queryParams.deliverId = props.deliverId
        getReceivingByDeliverId()
      } else if (props.orderId) {
        filterInfo.query.queryMap.orderId.value = props.orderId
        getMain()
      }
      getDeoptLeftCustomize()
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置
  let param = {
    tableKey:
      'stockReceivingOrderQueryProduct-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      if (tableInfo.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'deliverDetailId',
        })
      }
      tableInfo.sysGroup = arr
    }
  })
}
function getSingleVo() {
  let param = {
    tableKey:
      'stockReceivingOrderSingleModify-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      singleProductInfo.customizeUserVO = res.data
    }
  })
}
function getLeftCustomize() {
  let param = {
    tableKey:
      'stockReceivingOrderSingleModifyLeft-com.slip.spd.entity.vo.stock.ReceivingOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      singleProductInfo.leftCustomizeUserVO = data
    }
  })
}

//打开选择收货地址窗口
function openReceiveAddressWindow() {
  selectReceiveAddressInfo.visible = true
}
function selectReceiveAddressCallback(data) {
  if (data) {
    formInfo.data.receiveAddressValue = data.addressValue
    formInfo.data.receiveProvince = data.province
    formInfo.data.receiveCity = data.city
    formInfo.data.receiveCounty = data.county
    formInfo.data.receiveAddress = data.address
    formInfo.data.receivingContacts = data.contacts
    formInfo.data.receivingPhone = data.contactsPhone
  }
}
</script>

<style scoped lang="scss">
:deep(.select) {
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  width: 100%;
  height: 28px;
  padding: 0 15px;
  box-sizing: border-box;
  border-radius: 4px;
  color: #606266;
  font-size: 12px;
  border: 1px solid #dcdfe6;

  :deep(option) {
    font-size: 12px;
    background: #6dc1a9 !important;
  }

  :deep(option:hover) {
    background: #6dc1a9 !important;
  }
}
.tips-desc {
  display: flex;
  flex-direction: row;
}
</style>
